from django import http
from django.contrib.auth import login

from django.shortcuts import render, redirect
import re
# Create your views here.
from django.urls import reverse
from django.views import View
from django.db import DatabaseError

from .models import User


class RegisterView(View):
    """用户注册"""
    def get(self,request):
        """提供注册页面
        接收到get请求后
        return Register.html页面
        """
        return render(request,'register.html')
    def post(self,request):
        # 接收前端注册页面发送的注册数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 后端校验数据
        # 1，判断参数是否齐全
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden("缺少必要的参数")
        # 2，判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        # 3，判断密码是否是8-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$',password):
            return http.HttpResponseForbidden('请输入长度为8-20位的密码')
        if password2 != password:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except DatabaseError:
            return render(request,'register.html',{'register_errmsg':'注册失败'})
        login(request, user)
        return redirect(reverse('contents:index'))
        # return http.HttpResponse("注册成功")
